const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const cors = require('cors')
const PORT = process.env.PORT || 8080

// 解决跨域
app.use(cors())

// 设置静态文件目录
app.use('/uploads', express.static('uploads'));

app.use(bodyParser.json())
// 配置解析表单数据的中间件
app.use(express.urlencoded({ extended: false }))

// 封装res.cc函数
app.use((req, res, next) => {
    // status默认值为1，表示失败的情况
    res.cc = function (err, status = 1, code = 40000) {
        res.send({
            status,
            code,
            message: err instanceof Error ? err.message : err
        })
    }
    next()
})

// 在路由之前配置解析Token的中间件
const expressJWT = require('express-jwt')
const config = require('./config')

app.use(expressJWT({ secret: config.jwtSecretKey }).unless({ path: [/^\/my/, /^\/api\/upload/] }))

// 导入登录注册路由模块
const userLoginRouter = require('./router/userLogin')
app.use('/my', userLoginRouter)

// 导入并使用路由模块
const userRouter = require('./router/user')
const mallRouter = require('./router/mall')
const currentUserRouter = require('./router/currentUser') 
const uploadRouter = require('./router/upload')
app.use('/api', userRouter)
app.use('/api', mallRouter)
app.use('/api', currentUserRouter)
app.use('/api', uploadRouter)

// 定义错误级别的中间件
app.use((err, req, res, next) => {
    // 身份认证失败后的错误
    if (err.name === 'UnauthorizedError') return res.cc('身份认证失败!')
    // 未知的错误
    res.cc(err)
})

// 启动服务器
app.listen(PORT, () => {
    console.log(`Server is running at http://127.0.0.1:${PORT}`)
})

